//
//  EventsTableDataViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/21/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "EventsTableDataViewController.h"
#import "StackMob.h"
#import "AddEventViewController.h"
#import "EventDetailsViewController.h"
#import "iBacchanal.h"
#import	"PartyAnimalAppDelegate.h"
#import "EventFlyersViewController.h"
#import "EventCell.h"
#import "UIImageView+AFNetworking.h"
#import "Reachability.h"

@implementation EventsTableDataViewController

@synthesize eventsTableData;
@synthesize eventsTableDataView;
@synthesize eventDetailsViewController;
@synthesize weeksCounter;
@synthesize contentView;

#pragma mark -
#pragma mark Initialization
-(void)reachabilityChanged:(NSNotification *)note{
	
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
	
	NetworkStatus netStatus = [curReach currentReachabilityStatus];
	//BOOL connectionRequired = [curReach connectionRequired];
	//NSLog(@"status: %@ ", connectionRequired);
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	switch (netStatus){
		case NotReachable:{
			//show an alert to let the user know that they can't connect...
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.downMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			bacchanal.networkUp = NO;
			self.navigationItem.rightBarButtonItem.enabled = NO;
			break;
		}
		default:{
			// Network is reachable
			UIAlertView *alert = [[[UIAlertView alloc] initWithTitle: nil message: bacchanal.upMessage
															delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil] autorelease];
			[alert show];
			[self refreshEventsData];
			bacchanal.networkUp = YES;
			self.navigationItem.rightBarButtonItem.enabled = YES;
			break;
		}
			
    }
}


-(void)buildEventsData{
	
	NSDate *date = [NSDate date];
	
	NSDateFormatter *weekFormat = [[NSDateFormatter alloc] init];
	[weekFormat setDateFormat:@"w"];
	//NSString *weekDateString = [weekFormat stringFromDate:date];
	NSInteger week  = [[weekFormat stringFromDate:date] intValue ];
	
	NSMutableArray *lastWeek = [[NSMutableArray alloc] init];
	NSMutableArray *thisWeek = [[NSMutableArray alloc] init];
	NSMutableArray *nextWeek = [[NSMutableArray alloc] init];
	NSMutableArray *upcoming = [[NSMutableArray alloc] init];
	NSMutableArray *unknown = [[NSMutableArray alloc] init];
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	
	for (NSDictionary *event in bacchanal.eventsData)		
	{
		if ( [[event objectForKey:@"hidden"] intValue] == 0){
			NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
			[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
			NSDate *tempdate = [dateFormat dateFromString:[event objectForKey:@"eventStart"]];
			[dateFormat setDateFormat:@"w"];
			NSInteger checkWeek = [[dateFormat stringFromDate:tempdate] intValue];
			
			if (checkWeek == (week - 1))
				[lastWeek addObject:event];
			else if(checkWeek == week)
				[thisWeek addObject:event];
			else if (checkWeek == (week + 1))
				[nextWeek addObject:event];
			else if (checkWeek > (week + 2))
				[upcoming addObject:event];
			else
				[unknown addObject:event];
			
		}	
	}
	
	eventsTableData = [[NSMutableArray alloc] initWithObjects:lastWeek, thisWeek, nextWeek, upcoming, unknown, nil];
	//NSLog(@"Events data: %@", eventsTableData);
	[lastWeek release];
	[thisWeek release];
	[nextWeek release];
	[upcoming release];
	[unknown release];
	[weekFormat release];
}


-(IBAction)findCloseEvents:(UIBarButtonItem *)sender{
	[eventsTableDataView reloadData];
}

-(IBAction)submitEvent:(UIBarButtonItem *)sender{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.loggedIn){
		
		AddEventViewController *addEventView = [[AddEventViewController alloc] initWithNibName:@"AddEvent" bundle:nil]; 
		UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:addEventView];
		[addEventView release];
		
		navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
		[self presentModalViewController:navController animated:YES];
		[navController release];
	}
	else{
		UIAlertView *msg = [[UIAlertView alloc] initWithTitle:nil message:@"You must be logged in to submit events. Goto the \"Account\" Tab to login in or create a new account" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[msg show];
		[msg release];
	}
}


-(void)refreshEventsData{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if ( bacchanal.eventsData == nil ||  bacchanal.dataChanged){
		NSLog(@"Events Table");
		StackMobQuery *q = [StackMobQuery query];
		[q setExpandDepth:2];
		
		
		[[StackMob stackmob] get:@"events" withQuery:q andCallback:^(BOOL success, id result) {
			if (success) {
				bacchanal.eventsData = [[NSMutableArray alloc] initWithArray:result];
				bacchanal.dataChanged = NO;
				[self buildEventsData];
				[eventsTableDataView reloadData];
				// object found, cast result to NSArray* and continue with processing
			}
			else {
				// unable to retrieve object, cast result to NSError* and inspect code & message
				NSLog(@"Error: %@", result);
			}
		}];
	}
}

// Helper function to size views
- (void)fixupAdView:(UIInterfaceOrientation)toInterfaceOrientation {
 	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBanner  != nil) {        
        if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
            [bacchanal.adBanner  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierLandscape];
        } else {
            [bacchanal.adBanner  setCurrentContentSizeIdentifier:
			 ADBannerContentSizeIdentifierPortrait];
        }
	
        [UIView beginAnimations:@"fixupViews" context:nil];
        if (bacchanal.adBanner.bannerLoaded) {
            CGRect adBannerFrame = [bacchanal.adBanner frame];
            adBannerFrame.origin.x = 0;
            adBannerFrame.origin.y = 0;
            [bacchanal.adBanner  setFrame:adBannerFrame];
            CGRect contentViewFrame = contentView.frame;
            contentViewFrame.origin.y = [bacchanal getBannerHeight:toInterfaceOrientation];
            contentViewFrame.size.height = self.view.frame.size.height - [bacchanal getBannerHeight:toInterfaceOrientation];
            contentView.frame = contentViewFrame;
        } else {
			[self hideBanner:toInterfaceOrientation];
        }
        [UIView commitAnimations];
    }   
}

-(void)hideBanner:(UIInterfaceOrientation)toInterfaceOrientation{
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	CGRect adBannerFrame = [bacchanal.adBanner frame];
	adBannerFrame.origin.x = 0;
	adBannerFrame.origin.y = - [bacchanal getBannerHeight:toInterfaceOrientation];
	[bacchanal.adBanner  setFrame:adBannerFrame];
	CGRect contentViewFrame = contentView.frame;
	contentViewFrame.origin.y = 0;
	contentViewFrame.size.height = self.view.frame.size.height + [bacchanal getBannerHeight:toInterfaceOrientation];
	contentView.frame = contentViewFrame;            
 	
}

// Implement AdBannerViewDelegate
#pragma mark ADBannerViewDelegate

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (!bacchanal.adBanner.bannerLoaded) {                
        //bacchanal.adBannerIsVisible = YES;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
   	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.adBanner.bannerLoaded)
    {        
        //bacchanal.adBannerIsVisible = NO;
        [self fixupAdView:[UIDevice currentDevice].orientation];
    }
}


/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 self = [super initWithStyle:style];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	
	[super viewDidLoad];
	self.navigationItem.title = @"Events";
	
	//self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Near Me" style:UIBarButtonItemStylePlain target:self action:@selector(findCloseEvents:)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(submitEvent:)] autorelease];
    
	weeksCounter = [[NSArray alloc] initWithObjects:@"Last Week", @"This week", @"Next week", @"Upcoming", @"Other", nil];
	
	
}



-(void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	if (bacchanal.networkUp){
		[self refreshEventsData];
		self.navigationItem.rightBarButtonItem.enabled = YES;
	}
	else
		self.navigationItem.rightBarButtonItem.enabled = NO;
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(reachabilityChanged:) 
												 name:kReachabilityChangedNotification 
											   object:nil];
	bacchanal.adBanner.delegate = self;
	[self.view addSubview:bacchanal.adBanner];
	[self.view bringSubviewToFront:[iBacchanal sharedUser].adBanner];	
	[self fixupAdView:[UIDevice currentDevice].orientation];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */

 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
	 [self hideBanner:[UIDevice currentDevice].orientation];
	 [[iBacchanal sharedUser].adBanner removeFromSuperview];	 
 }


- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	//NSLog(@"Sections: %d", [eventsTableData count]);
	return [weeksCounter count];//[eventsTableData count]; //[eventsTableData count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	//NSLog(@"Rows: %d", [[eventsTableData objectAtIndex:section] count]);
	if ([[eventsTableData objectAtIndex:section] count] < 1){
		return 1;
	}
	else{
		return [[eventsTableData objectAtIndex:section] count];
	}
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	return [NSString stringWithFormat:@"%@ (%i)", [weeksCounter objectAtIndex:section], [[eventsTableData objectAtIndex:section] count]];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    ///static NSString *CellIdentifier = @"Cell";
    static NSString *CellIdentifier = @"EventCell";
    
    EventCell *cell = (EventCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if(cell == nil){
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"EventCell"
																 owner:nil options:nil];
		for (id currentObject in topLevelObjects) {
			if ([currentObject isKindOfClass:[UITableViewCell class]]) {
				cell = (EventCell *) currentObject;
				break;
			}
		}
	}
	
	/*UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	 
	 if (cell == nil) {
	 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
	 }*/
	
    
    // Configure the cell...
	if ([[eventsTableData objectAtIndex:indexPath.section] count] == 0){
		//[[cell textLabel] setText:@"No events found"];
		//[[cell detailTextLabel] setText:@""];
	}
	else{
		
		NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
		[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"];
		NSDate *tempdate = [dateFormat dateFromString:[[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex: indexPath.row] objectForKey:@"eventStart"] ];
		[dateFormat setDateFormat:@"EEE, MMM dd"];
		NSString *dateString = [NSString stringWithFormat:@"%@ (%@)",
								[[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex: indexPath.row] objectForKey:@"eventName"],
								[dateFormat stringFromDate:tempdate]];
		
		//[[cell textLabel] setText:dateString];
		
		//if ([[[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"eventLoc"] length] > 0)
		[[cell detailTextLabel] setText:[[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"eventLoc"]     ];
		cell.eventName.text = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"eventName"];
		cell.eventLocation.text = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"eventLoc"];
		
		NSArray *tempFliers = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"event_fliers"];
		NSLog(@"fliers: %@", tempFliers);
		if ([tempFliers count ] > 0){
			
			NSURL *url = [NSURL URLWithString:[[tempFliers objectAtIndex:0] objectForKey:@"flyer"]];
			UIImageView *testView = [[UIImageView alloc] init];
			[testView setImageWithURL:url];
			cell.flyerImage1.image = testView.image;
		}
		
	}
	
	return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 150;
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
	 *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	if ([[eventsTableData objectAtIndex:indexPath.section] count] > 0){
		
		
		iBacchanal *bacchanal = [iBacchanal sharedUser];;
		bacchanal.eventID = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"events_id"];
		bacchanal.eventName = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"eventName"];
		bacchanal.flyerSideOne = nil;
		bacchanal.flyerSideTwo = nil;
		bacchanal.eventSubmitter = [[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"submittedBy"];
		NSLog(@"%@ - %@", bacchanal.eventSubmitter, bacchanal.currentUser);
		bacchanal.eventFlyersArray = [[NSMutableArray alloc] init];
		
		
		NSArray *tempFliers = [[NSArray alloc] initWithArray:[[[eventsTableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] objectForKey:@"event_fliers"] ];
		NSLog(@"flier: %i", [tempFliers count]);
		if ([tempFliers count ] > 0){
			for (NSDictionary *flyer in tempFliers){
				
				[bacchanal.eventFlyersArray addObject: [flyer objectForKey:@"flyer"]];
				
			}
		}
		
		EventFlyersViewController *eventFlyersView = [[EventFlyersViewController alloc] initWithNibName:@"EventFlyers" bundle:nil]; 
		UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:eventFlyersView];
		[eventFlyersView release];
		
		navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
		[self presentModalViewController:navController animated:YES];
		[navController release];
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
	[contentView release];
	[weeksCounter release];
	[eventsTableData release];
	[eventsTableDataView release];
	[eventDetailsViewController release];
    [super dealloc];
}


@end

